package com.shanghaionstar.notifysetting;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.map.util.ToastUtil;
import com.onstar.cn.more.entity.FlowDataComplexType;
import com.onstar.cn.more.response.DataPackageEntity;
import com.onstar.cn.notify.NotifyConfigRes;
import com.onstar.cn.smart.entity.ServiceItem;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.more.CustomLineLayout;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.notifysetting.iview.INotifyView;
import com.shanghaionstar.notifysetting.presenter.NotifyPresenter;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.user.ChangeEmailOrPhoneFragment;
import com.shanghaionstar.user.presenter.OptPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.weight.TopLayout;

import java.util.List;

import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.CHANGE_FROM_NOTIFY;
import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.TYPE_CHANGE_EMAIL;
import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.TYPE_CHANGE_PHONE;
import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.TYPE_DA;
import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.TYPE_DS;
import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.TYPE_OL;
import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.TYPE_OVD;
import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.TYPE_TAN;
import static com.shanghaionstar.notifysetting.presenter.NotifyPresenter.IBType.TYPE_VI;

/**
 * Created by Yonglang Hong on 2017/3/17.
 */
@ContentView(R.layout.activity_setnotify)
public class SetNotifyActivity extends SwipeActivity implements INotifyView {
    public static final int NOTIFY_REQ = 100;

    @FindViewById
    private CustomLineLayout cll_setNotifyAN, cll_setNotifyOVD, cll_setNotifyDA, cll_setNotifyOL, cll_setNotifyVI, cll_setNotifyDS,
            cll_change_phone, cll_change_mail;
    @FindViewById
    private ProgressLayout progress_layout;
    @FindViewById
    private TopLayout top_layout;

    private NotifyPresenter mPresenter;

    private String type;
    private NotifyConfigRes mNotifyConfig;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new NotifyPresenter(getScheduler());
        mPresenter.setView(this);
        mPresenter.getNotifyConfig(TYPE_OVD);
        initView();
        if (ApplicationUtil.getInstance().isGen10()) {
            mPresenter.getDaServiceStatus(SetNotifyActivity.this);
        } else {
            cll_setNotifyDA.setVisibility(View.GONE);
        }
        if (!ApplicationUtil.getInstance().isGen10()) {
            if (!isCadillac()) {
                cll_setNotifyAN.setVisibility(View.GONE);
            }
        }

        top_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickBack.getStringValue());
                finish();
            }
        });

        showByServiceItem(OptPresenter.SMART_DRIVE, cll_setNotifyVI, cll_setNotifyDS);
        showByServiceItem(OptPresenter.FUEL_ECONOMY, cll_setNotifyOL);

    }

    public void showByServiceItem(String serviceName, CustomLineLayout... layouts) {
        ServiceItem item = ApplicationUtil.getInstance().getServiceItemByName(serviceName);
        if (item != null) {
            String optStatus = item.getOptStatus();
            if (optStatus.equalsIgnoreCase("0")) {
                for (CustomLineLayout layout : layouts) {
                    layout.setVisibility(View.GONE);
                }
            }
        }else {
            for (CustomLineLayout layout : layouts) {
                layout.setVisibility(View.GONE);
            }
        }
    }

    public boolean isCadillac() {
        Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
        if (vehicle == null)
            return false;
        String desc = vehicle.getModelDesc();
        return desc.contains("凯迪拉克") || desc.toLowerCase().contains("Cadillac".toLowerCase());
    }

    private void initView() {
        cll_change_phone.setRightText(getString(R.string.set_notify_go_setting));
        cll_change_mail.setRightText(getString(R.string.set_notify_go_setting));
    }

//    public boolean isCanSetDa() {
//        OnstarApplication mApp = OnstarApplication.getApplication();
//        Subscriber subscriber = mApp.getSubscriber();
//        String flag = subscriber.getRemindSetFlag();
//        return !TextUtils.isEmpty(flag) && flag.equalsIgnoreCase("1") ? true : false;
//    }

    @OnClick({R.id.cll_setNotifyAN, R.id.cll_setNotifyOVD, R.id.cll_setNotifyDA, R.id.cll_setNotifyOL, R.id.cll_setNotifyDS, R.id.cll_setNotifyVI, R.id.cll_change_phone, R.id.cll_change_mail})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cll_setNotifyAN:
                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickTANSetting.getStringValue());
                checkRole();
                break;
            case R.id.cll_setNotifyOVD:
                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickOVDSetting.getStringValue());
                mPresenter.getNotifyConfig(type = TYPE_OVD);
                break;
            case R.id.cll_setNotifyDA:
                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickDASetting.getStringValue());
                mPresenter.getNotifyConfig(type = TYPE_DA);
//                mPresenter.getDaServiceStatus(SetNotifyActivity.this);
                break;
            case R.id.cll_setNotifyDS:
//                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickDASetting.getStringValue());
                mPresenter.getNotifyConfig(type = TYPE_DS);
//                mPresenter.getDaServiceStatus(SetNotifyActivity.this);
                break;
            case R.id.cll_setNotifyVI:
//                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickDASetting.getStringValue());
                mPresenter.getNotifyConfig(type = TYPE_VI);
//                mPresenter.getDaServiceStatus(SetNotifyActivity.this);
                break;
            case R.id.cll_setNotifyOL:
                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickFuelEconomySetting.getStringValue());
                mPresenter.getNotifyConfig(type = TYPE_OL);
//                mPresenter.getDaServiceStatus(SetNotifyActivity.this);
                break;
            case R.id.cll_change_phone:
                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickMobilePhoneUpdate.getStringValue());
                type = TYPE_CHANGE_PHONE;
                checkLocalConfig(false);
                break;
            case R.id.cll_change_mail:
                BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.NotificationSettings_ClickEmailUpdate.getStringValue());
                type = TYPE_CHANGE_EMAIL;
                checkLocalConfig(true);
                break;
        }
    }


    private void checkLocalConfig(boolean isEmail) {
        if (CommonUtil.isNull(mNotifyConfig)) {
            mPresenter.getNotifyConfig(TYPE_OVD);
        } else {
            jumpToMore(mNotifyConfig, MoreActivity.class, isEmail);
        }
    }

//    private void checkExpired() {
////        服务包过期
//        if (ApplicationUtil.getInstance().isExpiredSubscriber()) {
//            Intent it = new Intent(this, SetANINotifyActivity.class);
//            startActivity(it);
//        } else {
//            mPresenter.getFlowData();
//        }
//    }

    private void checkRole() {
        String role = ApplicationUtil.getInstance().getLoginRole();
        if (!TextUtils.isEmpty(role) && role.equalsIgnoreCase(Constants.OWNER)) {
            if (ApplicationUtil.getInstance().isGen10()) {
                mPresenter.getFlowData();
            } else {
                if (ApplicationUtil.getInstance().isExpiredSubscriber()) {
                    Intent it = new Intent(this, SetANINotifyActivity.class);
                    startActivity(it);
                    return;
                }
                mPresenter.getNotifyConfig(type = TYPE_TAN);
            }
        }
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void onGetNotifyConfig(NotifyConfigRes notifyConfigRes) {
        if (initConfig(notifyConfigRes)) return;
        switch (type) {
            case TYPE_TAN:
                jumpToNotify(notifyConfigRes, SetANINotifyActivity.class);
                break;
            case TYPE_OVD:
                jumpToNotify(notifyConfigRes, SetOVDNotifyActivity.class);
                break;
            case TYPE_DA:
                jumpToNotify(notifyConfigRes, SetDANotifyActivity.class);
                break;
            case TYPE_DS:
                jumpToCommon(notifyConfigRes, NotifyPresenter.IBType.TYPE_DS);
                break;
            case TYPE_VI:
                jumpToCommon(notifyConfigRes, NotifyPresenter.IBType.TYPE_VI);
                break;
            case TYPE_OL:
                jumpToCommon(notifyConfigRes, NotifyPresenter.IBType.TYPE_OL);
                break;
            case TYPE_CHANGE_EMAIL:
                jumpToMore(notifyConfigRes, MoreActivity.class, true);
                break;
            case TYPE_CHANGE_PHONE:
                jumpToMore(notifyConfigRes, MoreActivity.class, false);
                break;
        }
    }

    private boolean initConfig(NotifyConfigRes notifyConfigRes) {
        if (TextUtils.isEmpty(type)) {
            mNotifyConfig = notifyConfigRes;
            setUpView(mNotifyConfig);
            return true;
        }
        return false;
    }

    private void setUpView(NotifyConfigRes mNotifyConfig) {
        cll_change_phone.setRightText(TextUtils.isEmpty(mNotifyConfig.getPhone()) ? getString(R.string.set_notify_go_setting)
                : CommonUtil.replaceString(mNotifyConfig.getPhone(), false));
        cll_change_mail.setRightText(TextUtils.isEmpty(mNotifyConfig.getMail()) ? getString(R.string.set_notify_go_setting)
                : CommonUtil.replaceString(mNotifyConfig.getMail(), true));
    }


    private void jumpToNotify(NotifyConfigRes notifyConfigRes, Class<?> clz) {
        Intent it = new Intent(SetNotifyActivity.this, clz);
        it.putExtra(type, notifyConfigRes);
        startActivity(it);
    }

    private void jumpToCommon(NotifyConfigRes notifyConfigRes, String type) {
        Intent it = new Intent(SetNotifyActivity.this, CommonNotifySetActivity.class);
        it.putExtra(NotifyPresenter.IBType.TYPE_COMMON, notifyConfigRes);
        it.putExtra("type", type);
        startActivity(it);
    }

    private void jumpToMore(NotifyConfigRes notifyConfigRes, Class<?> clz, boolean isEmail) {
        Intent it = new Intent(SetNotifyActivity.this, clz);
        Bundle phoneBundle = new Bundle();
        phoneBundle.putSerializable(CHANGE_FROM_NOTIFY, notifyConfigRes);
        phoneBundle.putString("jumpValue", isEmail ? notifyConfigRes.getMail() : notifyConfigRes.getPhone());
        phoneBundle.putBoolean("isEmail", isEmail);
        phoneBundle.putString(FinalConstants.JUMP_FLAG, ChangeEmailOrPhoneFragment.class.getName());
        it.putExtras(phoneBundle);
        startActivityForResult(it, NOTIFY_REQ);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == NOTIFY_REQ && data != null) {
            boolean isEmail = data.getBooleanExtra("isEmail", false);
            if (isEmail) {
                String email = data.getStringExtra("resultEmail");
                cll_change_mail.setRightText(TextUtils.isEmpty(email) ? getString(R.string.set_notify_go_setting)
                        : CommonUtil.replaceString(email, true));
            } else {
                String phone = data.getStringExtra("resultPhone");
                cll_change_phone.setRightText(TextUtils.isEmpty(phone) ? getString(R.string.set_notify_go_setting)
                        : CommonUtil.replaceString(phone, false));
            }

        }
    }


    @Override
    public void onGetNotifyConfigFailed() {
        ToastUtil.showShort(OnstarApplication.getApplication(), R.string.notify_setting_get_failed);
    }

    @Override
    public void onGetListPackage(DataPackageEntity entity) {
        boolean isNotOverDue = false;
        if (Float.parseFloat(entity.getTotalRemainUsage()) > 0) {
            isNotOverDue = true;
        }
        List<FlowDataComplexType> packageUsageInfos = entity.getPackageUsageInfos();
        if (!isNotOverDue && !CommonUtil.isNull(packageUsageInfos) && packageUsageInfos.size() > 0) {
            for (FlowDataComplexType info : packageUsageInfos) {
                if (info.getActive().equalsIgnoreCase("true") || !info.getRemainUsage().equalsIgnoreCase("0Byte")) {
                    isNotOverDue = true;
                }
            }
        }
        if (isNotOverDue)
            mPresenter.getNotifyConfig(type = TYPE_TAN);
        else {
            Intent it = new Intent(this, SetANINotifyActivity.class);
            startActivity(it);
        }
    }

    @Override
    public void onCheckStatusFailed(boolean isShow) {
        cll_setNotifyDA.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setLoading(boolean isLoading) {
        progress_layout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    @Override
    public void onReponseSuccess(Object object) {
        if (!CommonUtil.isNull(object) && object instanceof ServiceItem) {
//            mPresenter.getNotifyConfig(type = TYPE_DA);
        } else {

        }
    }

    @Override
    public Activity onActivity() {
        return this;
    }
}
